package org.zhaolei.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.zhaolei.config.OSSConfig;
import org.zhaolei.service.FileService;
import org.zhaolei.util.CommonUtil;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private OSSConfig ossConfig;

    @Override
    public String uploadUserImg(MultipartFile file) {

        //获取相关配置
        String bucketName = ossConfig.getBucketName();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //获取原生文件名
        String originalFilename = file.getOriginalFilename();

        //JDK8的日期格式，用日期做文件夹，然后再拼上文件的名称，原始文件名做MD5加密
        LocalDateTime ldt = LocalDateTime.now();  //获取当前时间
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd"); //自定义格式
        String folderName = dtf.format(ldt); //进行格式化

        //拼装路径，即OSS上的存储路径，比如 2020/07/01/xxxx.jpg
        String fileName = CommonUtil.generateUUID();
        //获取扩展名后缀
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = "user/" + folderName + "/" + fileName + extension;

        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, newFileName, file.getInputStream());
            //返回上传后的文件路径
            if (putObjectResult != null) {
                String imgUrl = "https://" + bucketName + "." + endpoint + "/" + newFileName;
                return imgUrl;
            }
        } catch (IOException e) {
            log.error("文件上传失败:{}", e);
        } finally {
            //OSS关闭服务，不然会一直占用资源，造成内存泄漏OOM
            ossClient.shutdown();
        }

        return null;
    }
}
